package test;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 加密解密工具类
 */
public class EncryptionUtils {

    /**
     * 随机生成16进制密钥
     * @return
     */
    public static String randomKey(){
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        BASE64Encoder enc=new BASE64Encoder();
        return enc.encodeBuffer(key);
    }

    /**
     * 根据密钥对指定字符串进行加密
     * @param key
     * @param val
     * @return
     */
    public static String encryptionString(String key,String val){
        try {
            BASE64Decoder dec=new BASE64Decoder();
            //构建
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, dec.decodeBuffer(key));
            //加密为16进制表示
            String encryptHex = aes.encryptHex(val);
            return encryptHex;
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 根据密钥对指定字符串进行解密
     * @param key
     * @param val
     * @return
     */
    public static String decryptionString(String key,String val){
        try {
            BASE64Decoder dec=new BASE64Decoder();
            //构建
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, dec.decodeBuffer(key));
            //加密为16进制表示
            String decryptStr = aes.decryptStr(val, CharsetUtil.CHARSET_UTF_8);
            return decryptStr;
        }catch (Exception e){
            return "";
        }
    }

    public static void main(String[] args) {
        String key = "+aRn/KCHBaL2Xfv3F3rroA==\n";
        String piece = "8e19c4e450642e04e87ddc5c4fb96b28";

        String s = EncryptionUtils.decryptionString(key,piece);
        System.out.println(s);
;    }

}
